package com.ydd.interceptor;

import com.ydd.constant.JwtClaimsConstant;
import com.ydd.context.BaseContext;
import com.ydd.properties.JwtProperties;
import com.ydd.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        // 获取request中的token
        String token = request.getHeader("token");
        if (token == null) {
            token = request.getHeader(jwtProperties.getTokenName());
        }
        log.info("获取到的token：{}", token);

        try {
            // 解析token
            Claims claims = JwtUtil.parseJWT(jwtProperties.getSecretKey(), token);
            String id = claims.get(JwtClaimsConstant.USER_ID).toString();
            log.info("解析出来的id：{}", id);

            // 将id存放在ThreadLocal中
            BaseContext.setCurrentId(id);

            // 解析成功放行
            return true;
        } catch (Exception e) {
            // 发送未认证错误信息  token过期  token解析异常
            log.info("token解析异常：{}", e.getMessage());
            response.setStatus(401);
            return false;
        }
    }
}
